/*
	Author: Joseph Montanez
	Liscence: GPL v2
	
*/

function initAjax () 
{		
	var xmlhttp=false;
	try 
	{
	  xmlhttp = new XMLHttpRequest();
	} 
	catch (trymicrosoft) 
	{
	  try 
	  {
		xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
	  } 
	  catch (othermicrosoft) {
		try 
		{
		  xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
		} 
		catch (failed) 
		{
		  xmlhttp = false;
		}
	  }
	}
	
	
	return xmlhttp;
}

function getAjax(url, afterFinish)
{
	var page = initAjax(); 
	var progress = document.getElementById(afterFinish.showStatus)
	if (!page)
	{
		// Error handle here
		// User alternative method (iframes?)
	}
	else
	{
		page.open('GET',url,true);
		page.onreadystatechange=function() {
			if (page.readyState == 0) 
			{
				if (progress)
					progress.innerHTML = "Uninitialized";
			}
			if (page.readyState == 1) 
			{
				if (progress)
					progress.innerHTML = "Loading";
				if ('function' == typeof afterFinish.onLoad)
					afterFinish.onLoad()
			}
			if (page.readyState == 2) 
			{
				if (progress)
					progress.innerHTML = "Loaded";
			}
			if (page.readyState == 3) 
			{
				if (progress)
					progress.innerHTML = "Interactive";
			}
			if (page.readyState == 4) 
			{
				if (page.status == 200)
				{
					result = page.responseText;
					if (progress)
						progress.innerHTML = "Complete";
					if ('function' == typeof afterFinish.onComplete)
						afterFinish.onComplete();
				}
				else
				{
					if (progress)
						progress.innerHTML = page.status+": "+page.statusText;
				}
			}
		}
		page.send(null);
	}

}

function postAjax(url,urlData, afterFinish)
{
	var page = initAjax(); 
	var progress = document.getElementById(afterFinish.showStatus)
	if (!page)
	{
		// Error handle here
		// User alternative method (iframes?)
	}
	else
	{
		page.open('POST',url,true);
		page.setRequestHeader ("Content-Type", "application/x-www-form-urlencoded")
		page.onreadystatechange=function() {
			if (page.readyState == 0) 
			{
				progress.innerHTML = "Uninitialized";
			}
			if (page.readyState == 1) 
			{
				progress.innerHTML = "Loading";
			}
			if (page.readyState == 2) 
			{
				progress.innerHTML = "Loaded";
			}
			if (page.readyState == 3) 
			{
				progress.innerHTML = "Interactive";
			}
			if (page.readyState == 4) 
			{
				if (page.status == 200)
				{
					result = eval(page.responseText);
					progress.innerHTML = "Complete";
					afterFinish.onComplete();
				}
				else
				{
					progress.innerHTML = page.status+": "+page.statusText;
				}
			}
		}
		page.send(urlData);
	}

}

function postForm(url, afterFinish)
{
	var myElements = document.forms[0].elements;
	var urlData = "";
	for (i=0; i < myElements.length; i++)
	{
		var myElement = myElements[i];
		if (myElement.className != "noSend")
		{
			urlData += myElement.name+"="+myElement.value+"&";
		}
	}
	urlData = urlData.substring(0,urlData.length-1);
	//DEBUG: alert("Url: "+url+"\nData: "+urlData+"\nonFinish: "+afterFinish);
	postAjax(url,urlData, afterFinish);
}